<template>
    <div class="dh_register_brand">
        <!-- 列表数据 pageingstate !== 2-->
        <div class="dhrb_s-content" v-if="pageingstate !== 2">

            <div class="dhrb_s-c-inquire bcwh br5">

                <el-form :model="kindinquire" ref="kindinquire" :rules="rules" :inline="true" label-width="80px" class="dh_sci-form mb10 pl10 pr10">
                    <el-form-item label="查询项" class="mt20 mb20">
                        <el-select v-model="kindinquire.select" @change="resetForm('kindinquire')">
                            <el-option label="商标文字" value="1"></el-option>
                            <el-option label="类别查询" value="2"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item prop="word" label="商标文字" v-if="kindinquire.select === '1'" class="mt20 mb20">
                        <el-input v-model="kindinquire.word" placeholder="请输入商标文字"></el-input>
                    </el-form-item>

                    <el-form-item prop="kind" label="查询大类" class="mt20 mb20" v-else>
                        <el-select v-model="kindinquire.kind">
                            <el-option v-for="(item,key) in kindselect" :key='key' :label="item.name" :value="item.name"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item class="mt20 mb20">
                        <el-button type="primary" @click="seektrade('kindinquire')" class="p10 f18">查询</el-button>
                        <el-button type="danger" @click="requesttrade();resetForm('kindinquire')" class="p10 f18">取消查询</el-button>
                    </el-form-item>
                </el-form>

            </div>

            <div class="dhrb_s-c-list">
 
                <div class="dhrb_scl-title df mb10 pb10 bb1">
                    <div>
                        <span class="bc4a p5 wh f14 dib br5" @click="pageingstate = 2;generating=0;entireclassify();currentPage3=1" >添加商标表</span>
                        <span class="bc4a p5 wh f14 dib br5 mr10 rel" @click="pageingstate=1;total=numday.number;requesttrade()">今日<span v-if="numday.number!==0" class="dhrb_scl-day">{{numday.number}}</span></span><span @click="pageingstate=0;requesttrade()" class="bc4a p5 wh f14 dib br5">总量</span>
                    </div>
                    <div>
                        <span v-if="formapply.state === false">
                            <span v-if="coding.manage">管理员</span> 
                            <!-- <button v-else type="button" @click="formapply.state=true" class="bc4a p5 wh f14 br5">申请</button> -->
                            <div v-else><button v-if="numday.state !== 0" type="button" @click="formapply.state=true" class="bc4a p5 cup wh f14 br5">申请</button><span v-else class="bgb3 cuna p5 wh dib f14 br5">申请中</span></div>
                        </span>
                        
                        <el-form v-else label-width="70" :model="formapply" ref="formapply" :rules="rules" :inline="true" size="mini" class="dhrb_sclt-form">
                            <el-form-item label="申请理由" prop="reason">
                                <el-input v-model="formapply.reason"></el-input>
                            </el-form-item>
                            <el-form-item>
                                <el-button @click="shelfswitch('formapply')">提交</el-button>
                            </el-form-item>
                        </el-form>
                    </div>
                </div>
                <!-- 数据列表 -->
                <!-- <div class="bb1 mb10 pb10"><button type="button" @click="pageingstate = 3" class="pt5 pr10 pb5 pl10 br5 wh bc4a">添加员工</button></div> -->
                <table class="dhrb_scl-table tc f14">
                    <thead>
                        <tr v-if="pageingstate === 1">
                            <th>所属员工ID</th>
                            <th>申请人名称<br/><span class='n f12 b00a'>*姓名后的蓝色图标点击看详情</span></th>
                            <th>申请人地址</th>
                            <th>商标文字</th>
                            <th>类别</th>
                            <th>文件名称</th>
                            <th>创建时间</th>
                            <th>操作</th>
                        </tr>
                        <tr v-else>
                            <th>所属员工ID</th>
                            <th>申请人名称<br/><span class='n f12 b00a'>*姓名后的蓝色图标点击看详情</span></th>
                            <th>申请人地址</th>
                            <th>商标文字</th>
                            <th>类别</th>
                            <th>文件名称<span class="b00a cup" @click="requerstexcel">(导出Excel)</span></th>
                            <th>创建时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>

                    <tbody v-if="pageingstate === 1">
                        <tr v-for="(item,key) in tradelist.slice(0,(numday.number-((currentPage-1)*pagesize)))" :key="key">
                            <td>{{item.staffid}}</td>
                            <td>{{item.name}}
                                <router-link :to="'/details/'+item.id" ><i class='el-icon-folder-opened f18 b00a'></i></router-link><!--@click="examine(item.id)"-->
                            </td>
                            <td>{{item.address}}</td>
                            <td>{{item.word}}</td>
                            <td>{{item.kind}}</td>
                            <!-- <td><span @click="generatedoc(item)">{{item.filename}}</span></td> -->
                            <td>{{item.filename}}</td>
                            <td>{{item.createtime*1000 | formatDate}} {{item.createtime*1000 | formatDateBehind}}</td>
                            <td>
                                <button type="button" @click="dialogFormVisible=true;for(var i in tradeupdata) i!=='arrgoods' ? tradeupdata[i]=item[i] : '';tradeupdata.key=key;tradeupdata.arrgoods = []" class="wh pt5 pr10 pb5 pl10 br5 bc4a">修改</button>
                                <!-- <button type="button" @click="staffdelete(item.id,key)" class="wh pt5 pr10 pb5 pl10 br5 bcfd">删除</button> -->
                                <button type="button" @click="download(item)" class="wh pt5 pr10 pb5 pl10 br5 bcfb">下载</button>
                            </td>
                        </tr>
                    </tbody>
                    <tbody v-else>
                        <tr v-for="(item,key) in tradelist" :key="key">
                            <td>{{item.staffid}}</td>
                            <td>{{item.name}}
                                <router-link :to="'/details/'+item.id" ><i class='el-icon-folder-opened f18 b00a'></i></router-link><!--@click="examine(item.id)"-->
                            </td>
                            <td>{{item.address}}</td>
                            <td>{{item.word}}</td>
                            <td>{{item.kind}}</td>
                            <!-- <td><span @click="generatedoc(item)">{{item.filename}}</span></td> -->
                            <td>{{item.filename}}</td>
                            <td>{{item.createtime*1000 | formatDate}} {{item.createtime*1000 | formatDateBehind}}</td>
                            <td>
                                <button type="button" @click="dialogFormVisible=true;for(var i in tradeupdata) i!=='arrgoods' ? tradeupdata[i]=item[i] : '';tradeupdata.key=key;tradeupdata.arrgoods = [];currentPage3 = 1" class="wh pt5 pr10 pb5 pl10 br5 bc4a">修改</button>
                                <!-- <button type="button" @click="staffdelete(item.id,key)" class="wh pt5 pr10 pb5 pl10 br5 bcfd">删除</button> -->
                                <button type="button" @click="download(item)" class="wh pt5 pr10 pb5 pl10 br5 bcfb">下载</button>
                            </td>
                        </tr>
                    </tbody>
                </table>
                <!-- 分页 -->
                <div class="dhrb_scl-block bt1 bcwh">
                    <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page.sync="currentPage"
                    :page-sizes="[5, 10, 15, 20]"
                    :page-size="pagesize"
                    layout="total, sizes, prev, pager, next"
                    :total="total"
                    class=" pt5 pr10 pb5 pl10">
                    </el-pagination>
                </div>
            </div>

            <el-dialog title="修改员工信息" :visible.sync="dialogFormVisible" center :append-to-body='true' top="20vh" width="450px">

                <el-dialog width="40%" title=增加产品 :visible.sync="innerVisible" center append-to-body>
                    <div><span v-for="(item,key) in tradeupdata.arrgoods" :key="key" :class="['wh dib p2 mt5 mb5 ml5 mr5 br5 f12 wpnp',item.b === true ? 'bc4a' : 'bgb3']">{{item.a}}<span @click="cancel(item,key)"><i class="el-icon-close"></i></span></span></div>
                    <!-- <span class="wh bgb3 pt2 pb2 pl5 br5 f12 mr5 wpnp" v-for="(item,key) in tradeadd.arrgoods" :key="key">{{item.a}}<span @click="cancel(item,key)"><i class="el-icon-close"></i></span></span></div> -->
                    <div class="add-list bor1 br5">
                        <div class="add-list-titel bb1">
                            <div class="a-l-t-input ml10"><el-input size="mini" placeholder="请输入内容" v-model="input1"></el-input></div>
                            <button class="bc4a br5 wh p5" type="button" @click="seekclassify">搜索</button>
                        </div>
                        <div><span @click="pitchon(items,keys)" class="wh bgb3 dib p2 mt5 mb5 ml5 mr5 br5 f12 bgb3 wpnp" v-for="(items,keys) in allsamllclass" :key="keys">{{items.a}}</span></div>
                        <div class='bt1'><el-pagination @current-change="optionalskip" :current-page.sync="currentPage3" :page-size="30" layout="total, prev, pager, next, jumper" :total="total3"></el-pagination></div>
                    </div>
                    <div slot="footer" class="dialog-footer">
                        <el-button @click="innerVisible = false">添加</el-button>
                    </div>
                </el-dialog>

                <p class="dxm-ltb-text tc red">*灰色是原信息，填好修改信息后点击确定，信息自动更新</p>

                <div class="dxm-ltb-message mt20 df">
                    <span class="xm-ltbm-title">商标文字</span>
                    <el-input class="dxm-ltbm-price" v-model="tradeupdata.address" max="220px" placeholder="请输入新的注册地址" clearable></el-input>
                </div>

                <div class="dxm-ltb-message mt20 df">
                    <span class="xm-ltbm-title">注册地址</span>
                    <el-input class="dxm-ltbm-price" v-model="tradeupdata.word" max="220px" placeholder="请输入新的商标文字" clearable></el-input>
                </div>

                <div class="dxm-ltb-message mt20 df">
                    <span class="xm-ltbm-title">新增产品</span>
                    <div><span v-for="(item,key) in tradeupdata.arrgoods" :key="key" v-if="item.b!==true" class="wh dib p2 mt5 mb5 ml5 mr5 br5 f12 wpnp bc4a">{{item.a}}<span @click="tradeupdata.arrgoods.splice(key,1)"><i class="el-icon-close"></i></span></span></div>
                    <span @click="innerVisible=true;entireclassify();upexamine(tradeupdata.id)"><i class="el-icon-circle-plus-outline f30 b00a"></i></span>
                </div>

                <div class="dxm-ltb-confirm mt20 tc">
                    <el-button type="primary" class="dxm-ltb-c-btn wh" @click="requestupdata">确定</el-button>
                </div>
                
            </el-dialog>

        </div>

        <!-- 添加页面 -->
        <div class="dhrb_s-addgoods bcwh" v-else>
            <div class="bb1 p10 mb10">
                <button @click="pageingstate = 0" class="f14 bc4a p5 br5 wh"><i class='el-icon-arrow-left'></i>返回列表</button>
                <button type="button" class="f14 bc4a p5 br5 wh" @click="generating=0;for(var l in tradeadd)l!=='code' && l!=='arrgoods' ? tradeadd[l]='' : '';tradeadd.arrgoods=[]">重选模式</button>
            </div>
            
            <div class="dhrb_s-a-select" v-if="generating === 0">
                <button @click="generating = 1" type="button" class="bcf6 br5">随机生成</button>
                <button @click="generating = 2" type="button" class="bc4a br5">模板生成</button>
                <button @click="generating = 3" type="button" class="bcfb br5">自选生成</button>
            </div>

            <el-form v-else :model='tradeadd' ref="tradeadd" :rules="rules" label-width="90px" class="dhrb_s-a-form p10">

                <el-form-item label="申请人名称" prop="name">
                    <el-col :span="6"><el-input v-model="tradeadd.name" placeholder="商标注册表申请人" clearable></el-input></el-col>
                </el-form-item>

                <el-form-item label="申请人地址" prop="address">
                    <el-col :span="6"><el-input v-model="tradeadd.address" placeholder="申请人的公司地址或家庭住址" clearable></el-input></el-col>
                </el-form-item>

                <el-form-item label="商标文字" prop="word">
                    <el-col :span="6"><el-input v-model="tradeadd.word" placeholder="注册商标的文字" clearable></el-input></el-col>
                </el-form-item>
                
                <el-form-item label="商标的大类" prop="kind">
                    <!-- <el-radio @change="option" v-model="tempform.kindAllid" v-for="(item,key) in kindselect" :key='key' :disabled="pageingstate===4 ? true : false" :label="item.id">{{item.name}}</el-radio> -->
                    <el-select v-model="tradeadd.kind" @change="requestsubclass">
                        <el-option v-for="(item,key) in kindselect" :key='key' :label="item.name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                
                <el-form-item label="文件名称:">
                    <el-button type="primary" @click="generatename('tradeadd')">生成</el-button>
                    <span>{{tradeadd.filename}}</span>
                </el-form-item>

                <!-- 三种模式 -->
                <el-form-item label="" v-if="tradeadd.kind !== ''">
                    <label slot="label">
                        <span v-if="generating === 1">随机生成</span>
                        <span v-else-if="generating === 2">选择模板</span>
                        <span v-else>自选小类</span>
                    </label>
                    <el-button @click="randomsort" v-if="generating === 1" type="primary">生成小类</el-button>
                    <el-radio v-else-if="generating === 2" @change="option" v-model="tradeadd.kindAllid" v-for="(item,key) in tradeoption" :key='key' :disabled="pageingstate===4 ? true : false" :label="item.id">{{item.name}}</el-radio>
                    <div class="add-list bor1 br5" v-else>
                        <div class="add-list-titel bb1">
                            <div class="a-l-t-input ml10"><el-input size="mini" placeholder="请输入内容" v-model="input1"></el-input></div>
                            <button class="bc4a br5 wh p5" type="button" @click="seekclassify">搜索</button>
                        </div>
                        <div><span @click="pitchon(items,keys)" class="wh bgb3 p5 br5 f12 ml5 mr5 wpnp" v-for="(items,keys) in allsamllclass" :key="keys">{{items.a}}</span></div>
                        <div class='bt1'><el-pagination @current-change="optionalskip" :current-page.sync="currentPage3" :page-size="30" layout="total, prev, pager, next, jumper" :total="total3"></el-pagination></div>
                    </div>  

                </el-form-item>

                <el-form-item label="模板小类" v-if="tradeadd.kind !== ''">
                    <div v-if="generating !== 3"><span class="pl5 pr5 b00a" v-for="(items,keys) in tradeadd.arrgoods" :key="keys">{{keys+1}}.{{items.a}}</span></div>
                    <div v-else><span class="wh bgb3 pt2 pb2 pl5 br5 f12 mr5 wpnp" v-for="(item,key) in tradeadd.arrgoods" :key="key">{{item.a}}<span @click="cancel(item,key)"><i class="el-icon-close"></i></span></span></div>
                </el-form-item>
                
                <el-form-item>
                    <el-button type="primary" @click="updatatrade('tradeadd')">提交</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script>
import {date} from '../js/time.js';  			 //用于时间戳转换时间
import {timetamp} from '../js/time.js'		 //用户日期转时间戳
import {timeday} from '../js/time.js'
import {formatDate} from '../js/time.js';		 //直接在标签中转化时间的方法
const axios = require('axios');
export default {
    components: {},
    data() {
        return {
            token: '',                          //后台的验证令牌
            coding: '',                         //员工的身份id
            kindselect: [],                    //做类别名过滤用的
            allsamllclass:[],                  //全部小类的数组
            // 查询的绑定值
            kindinquire:{
                select: '1',
                word: '',
                kind: ''
            },
            // 模板数组
            tradeoption:[],
            // 添加商标注册标的绑定对象
            tradeadd:{
                name: '',
                address: '',
                word: '',
                kind: '',
                filename: '',
                createtime: '',
                kindAllid:'',
                arrgoods:[],
                code:''
            },
            // 修改
            tradeupdata:{
                id:'',
                address:'',
                word: '',
                arrgoods:[],
            },
            rules:{
                name:[
                    { required: true, message: '请输申请人名称', trigger: 'blur' },
                ],
                address:[
                    { required: true, message: '请输申请人地址', trigger: 'blur' },
                ],
                word:[
                    {required: true, message: '请输入商标文字', trigger: 'blur'}
                ],
                kind:[
                    {required: true, message: '请选择商标的大类', trigger: 'change'}
                ],
                reason:[
                    {required: true, message: '申请理由不能为空', trigger: 'blur'}
                ]
            },
            generating: 0,                     //商标注册表生成的模式
            // 初始的数据列表
            tradelist:[],
            pageingstate: 0,                   //彩笔使用的分页状态管理（区分数据运行）
            currentPage: 1,					   //分页的默认页数
            pagesize: 10,                      //单页条数
            total: 0,						   //总条数
            numday: {
                time:'',
                number: 0,
                state: ''               //申请的状态
            },                        //每日数量
            currentPage3: 1,
            total3: 0,
            input1: '',
            dialogFormVisible: false,
            innerVisible:false,
            // 申请
            formapply:{
                reason: '',
                state: false
            }
        };
    },
    filters:{
        formatDate(time){
            var date = new Date(time);
            return formatDate(date,'yyyy-MM-dd')
        },
        formatDateBehind(time){
            var date = new Date(time);
            return formatDate(date,'hh:mm:ss')
        }
    },
    computed: {},
    watch: {},
    methods: {
        // 初始数据
        requesttrade(){
            let that = this;
            let data = {current:that.currentPage,size:that.pagesize,staffid:that.coding.id};
            that.coding.manage === 1 ? delete data.staffid : ''
            let updata = JSON.stringify(data);
            axios({
                method:'post',
                url: '/api/trademarkInfo/list',
                headers:{
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                data: updata
            }).then( resp=> {
                // console.log(resp)
                // that.pageingstate = 0;
                if(that.pageingstate === 0){
                    that.tradelist = resp.data.data;
                    that.total = resp.data.code;
                }else if(that.pageingstate === 1){
                    that.tradelist = resp.data.data;
                }else{return}
            }).catch( err=> {})
        },

        // 每日数量
        async requestday(){
            let that = this;
            var date = new Date();
            var year = date.getFullYear();
            var month = date.getMonth() + 1;
            var day = date.getDate();
            if (month < 10) {
                month = "0" + month;
            }
            if (day < 10) {
                day = "0" + day;
            }
            that.numday.time = timetamp(year + "-" + month + "-" + day+' '+'00:00:00')
            let total = 10,select;
            for(var i=0;i<2;i++){
                let data = {
                    current:that.currentPage,
                    size:total,
                    createTime: that.numday.time,
                    staffid:that.coding.id
                };
                that.coding.manage === 1 ? delete data.staffid : ''
                let updata = JSON.stringify(data);
                await axios({
                    method:'post',
                    url: '/api/dayNum/list',
                    headers:{
                        'Content-Type': 'application/json',
                        'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                    },
                    data: updata
                }).then( resp=> {
                    // console.log(resp)
                    if(i===0){
                        resp.data.code <= 10 ? (
                            resp.data.data.forEach((item)=>{
                                that.numday.number += Number(item.number)
                            }),
                            that.numday.id = resp.data.data[0].id,i=2
                        ) : total = resp.data.code
                    }else{
                        for(var x=0;x<resp.data.data.length;x++){
                            that.numday.number += resp.data.data[x].number
                        }
                        that.numday.id = resp.data.data[0].id
                    }
                    // console.log(that.numday.number)
                }).catch( err=>{})
            }
        },

        // 申请查询
        requestapply(){
            let that = this;
            let data = {current: 1,size: 10};
            // that.coding.manage === 0 ? data.manage = 1 : (this.$message.error('您现在已经成为管理员!请不要重复申请'));
            let updata = JSON.stringify(data)
            axios({
                method: 'post',
                url: "/api/apply/list",
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`,
                },
                data: updata
            })
            .then( resp=> {})
            .catch( err=> {})
        },

        // 提交申请
        shelfswitch(formName){
            let that = this;
            var date = new Date();
            var year = date.getFullYear();
            var month = date.getMonth() + 1;
            var day = date.getDate();
            if (month < 10) {
                month = "0" + month;
            }
            if (day < 10) {
                day = "0" + day;
            }

            let data = {
                staffid: that.coding.id,
                applytime: timeday(year + "-" + month + "-" + day),
                reason: that.formapply.reason,
                applystate: 0
            };
            // that.coding.manage === 0 ? data.manage = 1 : (this.$message.error('您现在已经成为管理员!请不要重复申请'));
            let updata = JSON.stringify(data)
            this.$refs[formName].validate((valid) => {
            if (valid) {
                // alert('submit!');

                axios({
                    method: 'post',
                    url: "/api/apply/add",
                    headers: {
                        'Content-Type': 'application/json',
                        'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`,
                    },
                    data: updata
                })
                .then( resp=> {
                    // console.log(resp)
                    if(resp.data.message === "请求成功"){
                        that.formapply.state = false
                        that.$message({
                            message:'申请成功，请等待通过！',
                            type: 'success'
                        })
                    }else{return}
                })
                .catch( err=> {})

            } else {return false;}
            });
        },

        // 拿到全部的注册商标表，用来做文件名的编号
        requestlength(){
            let that = this;
            let data = {current:that.currentPage,size:that.pagesize};
            let updata = JSON.stringify(data);
        
            axios({
                method:'post',
                url: '/api/trademarkInfo/list',
                headers:{
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                data: updata
            }).then( resp=> {
                // console.log(resp.data.data)
                that.tradeadd.code = resp.data.code;
            }).catch( err=> {})
        },

        // 修改的弹窗显示已添加的小类
        async upexamine(id){
            let that = this;
            if(that.tradeupdata.arrgoods == ''){
                // console.log('看看是不是每次都通过')
                let total = 10,select;
                for(var i=0;i<2;i++){
                    let data = {trademarkInfoid:id,current:1,size:total};
                    let updata = JSON.stringify(data);
                    await axios({
                        method: 'post',
                        url: '/api/goods/list',
                        headers: {
                            'Content-Type': 'application/json',
                            'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                        },
                        data: updata
                    }).then( resp=> {
                        // console.log(resp)
                        if(i===0){
                            resp.data.code <= 10 ? (select = resp.data.data.map((item)=>{ return {
                                    a: item['a'],
                                    b: true
                                }}),i=2) : total = resp.data.code;
                        }else{
                            select = resp.data.data.map((item)=>{
                                return {
                                    a: item['a'],
                                    b: true
                                }
                            })
                        }
                        // that.total = resp.data.code;
                    }).catch( err=> {})
                }
                select.forEach(item=> that.tradeupdata.arrgoods.unshift(item))
                // console.log(that.tradeupdata.arrgoods)
            }else{return}
        },

        // 修改的已有产品删除
        deletereferrrer(){
            let that = this;
            that.tradeupdata.arrgoods = that.tradeupdata.arrgoods.filter(item=> item.b!==true)
        },

        // 提交修改内容
        async requestupdata(){
            let that = this;
            that.tradeupdata.arrgoods = that.tradeupdata.arrgoods.filter(item=> item.b!==true)
            let api,data;
            // console.log(that.tradeupdata)
            for(var i=0;i<2;i++){
                if(i===0){
                    data = {};
                    for(var p in that.tradeupdata) 
                    p==='arrgoods' ? '' : data[p] = that.tradeupdata[p];
                    api = '/api/trademarkInfo/update';
                }else{
                    that.tradeupdata.arrgoods.forEach(item=> item.trademarkInfoid = that.tradeupdata.id)
                    data = that.tradeupdata.arrgoods;
                    api = '/api/goods/batchAdd'
                }
                let updata = JSON.stringify(data)

                await axios({
                    method: 'post',
                    url: api,
                    headers: {
                        'Content-Type': 'application/json',
                        'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                    },
                    data: updata
                }).then( resp=> {
                    // console.log(resp)
                    if(i === 0){
                        for(var l in data) that.tradelist[that.tradeupdata.key][l] = data[l]
                        that.tradeupdata.arrgoods == "" ? i=2 : '';
                    }
                    that.dialogFormVisible = false
                }).catch( err=> {})
            }
        },

        //验证状态的取消
        resetForm(formName) {
            this.$refs[formName].resetFields();
            for(var r in this.kindinquire) r != 'select' ? this.kindinquire[r] = '' : ''
        },

        // 查询
        seektrade(formkind){
            let that = this;
            this.$refs[formkind].validate((valid) => {
                if(valid) {
                    let data = {current:that.currentPage,size:that.pagesize,staffid:that.coding.id};
                    for(var t in that.kindinquire){
                        t!=='select' && that.kindinquire[t]!=='' ? data[t] = that.kindinquire[t] : '';
                    }
                    let updata = JSON.stringify(data);
    
                    axios({
                        method:'post',
                        url: '/api/trademarkInfo/list',
                        headers:{
                            'Content-Type': 'application/json',
                            'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                        },
                        data: updata
                    }).then( resp=> {
                        // console.log(resp)
                        this.$message({
                            message: '成功找到'+resp.data.data.length+'条数据',
                            type: 'success'
                        })
                        that.pageingstate = 0;
                        that.tradelist = resp.data.data;
                        that.total = resp.data.code;
                    }).catch( err=> {})
                }else{
                    return// this.$message.error('查询值不能为空')
                }
            })
        },
        
        // 分页的函数
        handleSizeChange(val) {
            // console.log(`每页 ${val} 条`);
            let that = this;
            this.pagesize = val;
            that.requesttrade()
        },
        handleCurrentChange(val) {
            // console.log(`当前页: ${val}`);
            let that = this;
            that.currentPage = val
            that.requesttrade()
        },

        // 拿到所有的大分类用作添加小分类选项使用，
        async requestselect(){
            let that = this;
            let total = 10,select;
            for(var i=0;i<2;i++){
                let data = {current:1,size:total,level:0};
                let updata = JSON.stringify(data);
            
                await axios({
                    method: 'post',
                    url: '/api/kindAll/list',
                    headers: {
                        'Content-Type': 'application/json',
                        'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                    },
                    data: updata
                }).then(resp=>{
                    // console.log(resp,resp.data.data)
                    if(i === 0){
                        resp.data.code <= 10 ? (
                            that.kindselect = resp.data.data.map((item)=>{
                                return {
                                    id: item['id'],
                                    name: item['name']
                                }
                            }),i=2) : total = resp.data.code;
                    }else{
                        that.kindselect = resp.data.data.map((item)=>{
                            return {
                                id: item['id'],
                                name: item['name']
                            }
                        })
                    }
                }).catch(err=>{})
            }
        },

        // 大类选择后获取的对应模板
        async requestsubclass(){
            let that = this;
            let total = 10,select;
            
            if(that.generating === 2){
                // console.log('好像没运行')
                that.tradeadd.arrgoods = [];
                for(var i=0;i<2;i++){
                    let data = {current:1,size:total,kindAllid:that.tradeadd.kind};
                    let updata = JSON.stringify(data);
    
                    await axios({
                        method: 'post',
                        url: '/api/template/list',
                        headers: {
                            'Content-Type': 'application/json',
                            'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                        },
                        data: updata
                    }).then(resp=>{
                        // console.log(resp,resp.data.data)
                        if(i === 0){
                            resp.data.code <= 10 ? (
                                that.tradeoption = resp.data.data.map((item)=>{
                                    return {
                                        id: item['id'],
                                        name: item['name']
                                    }
                                }),i=2) : total = resp.data.code;
                        }else{
                            that.tradeoption = resp.data.data.map((item)=>{
                                return {
                                    id: item['id'],
                                    name: item['name']
                                }
                            })
                        }
                    }).catch(err=>{})
                }

            }else{
                that.entireclassify()
            }
        },
        
        // 获取全部小类
        entireclassify(){
            let that = this;
            let data = {current:that.currentPage3,size:30,level:1};
            let updata = JSON.stringify(data);
            axios({
                method: 'post',
                url: '/api/kindAll/list',
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                data: updata
            }).then( resp=> {
                // console.log('全部的小类',resp)
                that.allsamllclass = resp.data.data.map((item)=>{
                    return {
                        a: item['name'],
                        b: item['namee']
                    }
                }) 
                that.total3 = resp.data.code;
            }).catch( err=> {})
        },
        // 自选的跳页
        optionalskip(val){
            let that = this;
            that.currentPage3 = val
            that.entireclassify()
        },

        // 获取对应模板的所有小类
        async option(){
            let that = this;
            let total = 10,select;
            for(var i=0;i<2;i++){
                let data = {current:1,size:total,templateid:that.tradeadd.kindAllid};
                let updata = JSON.stringify(data);

                await axios({
                    method: 'post',
                    url: '/api/templateKind/list',
                    headers: {
                        'Content-Type': 'application/json',
                        'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                    },
                    data: updata
                }).then(resp=>{
                    // console.log(resp,resp.data.data)
                    if(i === 0){
                        resp.data.code <= 10 ? (
                            that.tradeadd.arrgoods = resp.data.data.map((item)=>{
                                return {
                                    a: item['name'],
                                    b: item['namee']
                                }
                            }),i=2) : toatl = resp.data.code;
                    }else{
                        that.tradeadd.arrgoods = resp.data.data.map((item)=>{
                            return {
                                a: item['name'],
                                b: item['namee']
                            }
                        })
                    }
                }).catch(err=>{})
            }
        },

        // 生成文件名加表单验证
        generatename(formrules){
            let that = this;
            this.$refs[formrules].validate((valid) => {
                if (valid) {
                    let number = String(that.tradeadd.code).padStart(3,'0'),classes;
                    // console.log(number,that.tradeadd)
                    that.kindselect.forEach((item)=>{if(item.id === that.tradeadd.kind){ classes = item.name }})

                    var date = new Date();
                    var year = date.getFullYear();
                    var month = date.getMonth() + 1;
                    var day = date.getDate();
                    if (month < 10) {
                        month = "0" + month;
                    }
                    if (day < 10) {
                        day = "0" + day;
                    }
                    that.tradeadd.createtime = year + "-" + month + "-" + day;

                    that.tradeadd.filename = number+"--"+ that.coding.name+'-美国-'+that.tradeadd.name+'-'+that.tradeadd.word+'-'+classes+'-'+that.tradeadd.createtime+'.doc';
                    // console.log(that.tradeadd.filename)
                } else {return false;}
            });
        },

        // 添加商标注册信息
        async updatatrade(formrules){
            let that = this;
            let data,r=0,api,idname;
            this.$refs[formrules].validate((valid) => {
                if (valid) {
                    if(that.tradeadd.arrgoods != '' && that.tradeadd.filename !== ''){
                        
                    }else{this.$message.error('没有选择模板或者没有生成文件名'),r=2}
                }else{r=2}
            });
            for(r;r<2;r++){
                if(r===0){
                    data = {}
                    for(var o in that.tradeadd) o!=='kind' && o!=='kindAllid' && o!=='arrgoods' && o!=='code' ? data[o] = that.tradeadd[o] : '';
                    idname = that.kindselect.filter((item)=>{
                        if(that.tradeadd.kind == item.id){
                            return idname = item.name
                        }else{return}
                    })
                    data.kind = idname[0].name
                    data.createtime = timeday(data.createtime)
                    data.staffid = that.coding.id
                    api = "/api/trademarkInfo/add"
                }else{
                    data = that.tradeadd.arrgoods
                    api = '/api/goods/batchAdd'
                }
                let updata = JSON.stringify(data)
            
                await axios({
                    method: 'post',
                    url: api,
                    headers: {
                        'Content-Type': 'application/json',
                        'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                    },
                    data: updata
                }).then( resp=> {
                    console.log(resp)
                    if(r === 0){
                        that.tradeadd.arrgoods.forEach(item=>{
                            item.trademarkInfoid = resp.data.data;
                        })
                        data.id = resp.data.data
                        that.tradelist.unshift(data)
                        console.log(that.tradelist.unshift(data))

                        //生成文档
                        // console.log('生成',data)
                        let create = {};
                        for(var o in data) o!=='staffid' ? create[o] = data[o] : '';
                        create.staffid = that.coding.id
                        let upcreate = JSON.stringify(create)
                        console.log(upcreate)
                        setTimeout(()=>{
                            axios({
                                method:'post',
                                url: '/api/doc/exportDoc',
                                headers:{
                                    'Content-Type': 'application/json',
                                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                                },
                                data: upcreate
                            }).then( resp=> {
                                console.log(resp)
                            }).catch( err=>{})
                        },500)     
                    }else{
                        that.pageingstate = 0;
                        that.tradeadd.code += 1;
                        this.$message({
                            message: '添加成功',
                            type: 'success'
                        })

                        // 每日添加数量
                        let url
                        // console.log(that.numday.number)
                        that.numday.number === 0 ? (
                            url='/api/dayNum/add',that.numday.number = 1) :  (
                            url='/api/dayNum/update',that.numday.number += 1);
                        let day = {
                            id: that.numday.id,
                            createTime: that.numday.time,
                            staffid:that.coding.id,
                            number: that.numday.number
                        };
                        for(var o in day) day[o] ==='' ? delete day[o] : ''
                        let upday = JSON.stringify(day);
                        axios({
                            method:'post',
                            url: url,
                            headers:{
                                'Content-Type': 'application/json',
                                'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                            },
                            data: upday
                        }).then( resp=> {
                            for(var m in that.tradeadd) m!=='arrgoods' && m!=="code" ? that.tradeadd[m] = '' : (m!=="code" ? that.tradeadd[m] = [] : '');
                        }).catch( err=>{})

                        // 生成doc
                    }
                }).catch( err=> {})
            }   
        },

        // 删除
        staffdelete(id,key){
            let that = this;
            let data = {id: id};
            let updata = JSON.stringify(data);
            axios({
                method: 'post',
                url: '/api/trademarkInfo/delete',
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                data: updata
            }).then( resp=> {
                // console.log(resp)
                that.tradelist.splice(key,1)
            }).catch( err=> {})
        },

        // 随机生成15个小类
        randomsort(){
            let that = this;
            var a=[];
            that.tradeadd.arrgoods = []
            while (true){
                var isExists = false;
                // 获取box数组
                var random = parseInt( that.allsamllclass.length * (Math.random()));
                // 每次循环只能取到一个不重复的随机，所以15个就是15次循环的判断，判断当前随机数是否已经存在
                for (var i = 0; i < a.length; i++) {
                    if (random === a[i]) {
                        isExists = true;
                        break;
                    }
                }
                // 如果不存在，则添加进去
                if (!isExists)
                    a.push(random)
                // 如果有3位随机数了，就跳出
                if (a.length === 15)
                    break;
            }
            a.forEach(item=> that.tradeadd.arrgoods.push(that.allsamllclass[item]))
                    // console.log(a,that.tradeadd.arrgoods)
        },

        //自选的搜索分类
        async seekclassify(){
            // let data = {}
            let that = this;
            // console.log(that.input1)
            let data = {current:1,size:10,name:that.input1};
            let updata = JSON.stringify(data)
            await axios({
                method: 'post',
                url: '/api/kindAll/list',
                headers:{
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                data: updata
            }).then( resp=> {
                // console.log(resp)
                let transform = resp.data.data.map((item)=>{
                    return {
                        a: item['name'],
                        kindAllid: item['id'],
                        b: item['namee'],
                    }
                })
                // console.log(transform)
                if(resp.data.data.length!== 0){

                    this.$message({
                        showClose: true,
                        message: '搜索到'+resp.data.data[0].name+'相关数据',
                        type: 'success'
                    })

                    this.$confirm('是否添加该小类?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        // that.tempform.arrname.push(transform[0])
                        if(that.pageingstate === 2){
                            that.tradeadd.arrgoods.find(fruit => fruit.a === transform[0].a) === undefined ? (
                                that.tradeadd.arrgoods.push(transform[0]),
                                this.$message({type: 'success',message: '添加成功!'})
                            ) : (
                                this.$message.error('已选择的分类不能重复添加')
                            );
                        }else{
                            that.tradeupdata.arrgoods.find(fruit => fruit.a === transform[0].a) === undefined ? (
                                that.tradeupdata.arrgoods.push(transform[0]),
                                this.$message({type: 'success',message: '添加成功!'})
                            ) : (
                                this.$message.error('已选择的分类不能重复添加')
                            );
                        }

                        return
                        // this.$message({
                        //     type: 'success',
                        //     message: '添加成功!'
                        // });
                        // console.log(that.tempform.arrname)
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '取消添加'
                        });          
                    });
                }else{
                    this.$message.error('不存该校小类');
                }
                
            }).catch( err=> {})
        },

        cancel(item,key){
            let that = this;
            if(that.pageingstate === 2){
                that.tradeadd.arrgoods.splice(key,1)
                that.allsamllclass.find(fruit => fruit.a === item.a) === undefined ? (that.allsamllclass.push(item)) : '';
            }else{
                that.tradeupdata.arrgoods.splice(key,1)
                that.allsamllclass.find(fruit => fruit.a === item.a) === undefined ? (that.allsamllclass.push(item)) : '';
            }  
        },

        pitchon(item,key){
            let that = this;
            if(that.pageingstate === 2){
                that.tradeadd.arrgoods.find(fruit => fruit.a === item.a) === undefined ? (that.tradeadd.arrgoods.push(item),that.allsamllclass.splice(key,1)) : this.$message.error('已选择的分类不能重复添加');
            }else{
                that.tradeupdata.arrgoods.find(fruit => fruit.a === item.a) === undefined ? (that.tradeupdata.arrgoods.push(item),that.allsamllclass.splice(key,1)) : this.$message.error('已选择的分类不能重复添加');
            }
        },

        // 下载
        async download(item){
            
            let that = this;
            
            axios({
                method: 'get',
                url:"/api/file/download?fileName=" + item.filename,
                // data:userjson,
                headers:{
                    'Content-Type':'application/json'  ,//如果写成contentType会报错
                    // "Authorization": "berare dhzn447d75e30a3c8579cf0eff666d56a283",
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                responseType: 'blob', //二进制流
            })

            .then(function (res) {
                
                if(!res) return
                let blob = new Blob([res.data]
                // {type: 'application/vnd.ms-excel;charset=utf-8'},
                )
                let url = window.URL.createObjectURL(blob);
                let aLink = document.createElement("a");
                aLink.style.display = "none";
                aLink.href = url;
                aLink.setAttribute("download", item.filename);
                document.body.appendChild(aLink);
                aLink.click();
                document.body.removeChild(aLink); 
                window.URL.revokeObjectURL(url); 
            }).catch(function (error) {})
        },

        // excel表
        requerstexcel(){
            let that = this;
            // axios.get('/api/excel/exportExcel', {
            //     responseType: 'blob'
            axios({
                method: 'post',
                url: '/api/excel/exportExcel',
                headers:{
                    'Content-Type':'application/json',//如果写成contentType会报错
                    // "Authorization": "berare dhzn447d75e30a3c8579cf0eff666d56a283",
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                responseType: 'blob', //二进制流
            }).then( resp=> {
                console.log(resp)
                // let blob = resp.data;
                // const fileReader = new FileReader();
                // fileReader.readAsDataURL(blob);
                // fileReader.onload = (event) => {
                //     let a = document.createElement('a');
                //     let fileName = '数据表格.xls';
                //     a.download = fileName;
                //     document.body.appendChild(a);
                //     a.click();
                //     documnet.body.removeChild(a);
                // }
                // if(resp.data.message === '请求成功'){
                    
                    let blob = resp.data;
                    const fileReader = new FileReader(); // FileReader 对象允许Web应用程序异步读取存储在用户计算机上的文件的内容
                    fileReader.readAsDataURL(blob); // 开始读取指定的Blob中的内容。一旦完成，result属性中将包含一个data: URL格式的Base64字符串以表示所读取文件的内容
                    fileReader.onload = (event) => { // 处理load事件。该事件在读取操作完成时触发
                        // 新建个下载的a标签，完成后移除。
                        let a = document.createElement('a');
                        let _fileName = '数据表格.xls';
                        a.download = _fileName;
                        a.href = event.target.result; 
                        document.body.appendChild(a);
                        a.click();
                        document.body.removeChild(a);
                    }

            })
        },

        // 申请状态
        applyof(){
            let that = this;
            let data = {current:that.currentPage,size:that.pagesize};
            let updata = JSON.stringify(data);
            axios({
                method: 'post',
                url: '/api/apply/list',
                headers:{
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                data: updata
            })
            .then( resp=> {
                // console.log(resp)
                that.numday.state = resp.data.data[0].applystate;
                console.log(that.numday.state)
            }).catch( err=> {})
        },

        // 拿令牌
        requesttoken(){
            let that = this;
            let loguser = JSON.parse(sessionStorage.getItem('userdata'))
            let data = {username:loguser.username, password:loguser.password};
            let updata = JSON.stringify(data);
        
            axios({
                method: 'post',
                url: '/api/getAuthority/staff',
                headers: { 'Content-Type': 'application/json' },
                data: updata
            })
            .then( resp=> {
                // console.log(resp)
                if(resp.data.data !== '没有权限！'){
                    // that.token = resp.data.data;
                    // that.refreshing();
                    that.takeserial(data,resp.data.data)
                }
            })
            .catch( err=> {})
        },

        async takeserial(data,token,state){
            // console.log('接收值',data,token)
            let that = this
            data.current = 1;
            data.size = 10;
            let updata = JSON.stringify(data);
        
            await axios({
                method: 'post',
                url: '/api/staff/list',
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${token}`
                },
                data: updata
            }).then( resp=> {
                // console.log(resp)
                that.coding = {id:resp.data.data[0].id,name:resp.data.data[0].name,manage:resp.data.data[0].manage}
                that.token = token
                // console.log(that.coding,that.token)
                sessionStorage.setItem('coding',JSON.stringify(that.coding))
                sessionStorage.setItem('token',JSON.stringify(token))
                sessionStorage.setItem("userdata",JSON.stringify(data))

                that.requestday()
                that.applyof()
                that.requestapply()
                that.requesttrade()
                that.requestlength()
                that.requestselect()
            }).catch( err=> {})
        }
    },
    created() {
        this.requesttoken()
    },
    mounted() {
        let that = this;
        // that.coding = JSON.parse(sessionStorage.getItem('coding'))
        // that.token = JSON.parse(sessionStorage.getItem('token'));
        // that.requestday()
        // that.requestapply()
        // that.requesttrade()
        // that.requestlength()
        // that.requestselect()
    },
    beforeCreate() {},
    beforeMount() {},
    beforeUpdate() {},
    updated() {},
    beforeDestroy() {},
    destroyed() {},
    activated() {},
    }
</script>
<style scoped>
.dh_register_brand{
    height: 100%;
}
.dhrb_s-content{
    height: 100%;
}
.dhrb_s-c-inquire{
    box-shadow: 0 0 2px #4b4b4b;  
}
/* 查询 */
.dhrb_sci-form{
    background-color: #ffffff;
    box-shadow: 0 0 2px #4b4b4b;
    border-radius: 5px;
}
/* 列表数据 */
.dhrb_s-c-list{
    display: flex;
    flex-direction: column;
    height: calc(100% - 91px);
    padding: 10px;
    background-color: #ffffff;
    border-radius: 5px;
    box-sizing: border-box;
    box-shadow: 0 0 2px #4b4b4b;
}

/* 头部 */
.dhrb_scl-title{
    justify-content: space-between;
    align-items: center;
}
.dhrb_sclt-form .el-form-item--mini.el-form-item{
    margin: 0;
}

.dhrb_scl-table{
    width: 100%;
    border-collapse: collapse;
    border-bottom: 1px solid #e0e0e0;
    border-right: 1px solid #e0e0e0;
    border-spacing: 0;/*去掉单元格间隙*/
}
.dhrb_scl-table th{
    background-color: #ececec;
}
.dhrb_scl-table tbody tr:hover{
    background-color: #ececec;
}
.dhrb_scl-table th,.dhrb_scl-table td{
    padding: 10px 10px;
    border-left:1px solid #e0e0e0;
    border-top:1px solid #e0e0e0;
}

/* 修改的弹窗 */
.dxm-ltb-message{
    display: flex;
    align-items: center;
}
.xm-ltbm-title{
    min-width: 80px;
}
/* 分页 */
.dhrb_scl-block{
    margin-top: auto;
}

/* 添加 */
.dhrb_s-addgoods{
    background-color: #ffffff;
}

/* 生成模式的 */
.dhrb_s-a-select{
    padding: 10px;
    display: flex;
    justify-content: space-between;
}
.dhrb_s-a-select button{
    width: 30%;
    height: 100px;
    font-size: 30px;
    color: white;
}

/* 自选的搜索框 */
.a-l-t-input{
    display: inline-block;
    width: 180px;
}


/* 每日数量 */
.dhrb_scl-day{
    text-align: center;
    position: absolute;
    display: inline-block;
    top: -6px;
    right: -6px;
    min-width: 15px;
    min-height: 15px;
    /* padding: 3px; */
    color: #ffffff;
    background-color: #ff0000;
    border-radius: 50px;
}
</style>